package com.plugins.utils;


import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.plugins.App;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Create by 游德禄 on 2019-9-3
 * 公共工具
 */
public class CommonUtil {
    /**
     * 简短提示
     * @param mContext
     * @param text
     */
    public static void tip(Context mContext, String text) {
        Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
    }


    /**
     * 判断是否是手机号
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static boolean isChinaPhone(String str)
            throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
        return match(regExp, str);
    }

    /**
     * 判断是不是条码
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static boolean isBarcode(String str)
            throws PatternSyntaxException {
        String regExp = "^[0-9A-Z]+$";
        return match(regExp, str);
    }

    /**
     * 正则匹配
     * @param regExp
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static boolean match(String regExp, String str)
            throws PatternSyntaxException {
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 以什么开始
     * @param str
     * @param regExp
     * @return
     */
    public static boolean startWith(String str, String... regExp) {
        return exp(str, true, regExp);
    }

    /**
     * 以什么结尾
     * @param str
     * @param regExp
     * @return
     */
    public static boolean endWith(String str, String... regExp) {
        return exp(str, false, regExp);
    }

    private static boolean exp(String str, boolean isStart, String... regExp)
            throws PatternSyntaxException {
        String s = "";
        for (String st : regExp) {
            if (isStart) {
                s += st + "([\\s\\S]*?)|";
            } else {
                s += ".*" + st + "$|";
            }
        }
        s = s.substring(0, s.length() - 1);
        return match(s, str);
    }

    //获取版本号(内部识别号)
    public static int getVersionCode(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }




    /**
     * 字节单位转换
     * @param size
     * @return
     */
    public static String getPrintSize(long size) {
        //如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        //如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
        //因为还没有到达要使用另一个单位的时候
        //接下去以此类推
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            //因为如果以MB为单位的话，要保留最后1位小数，
            //因此，把此数乘以100之后再取余
            size = size * 100;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "MB";
        } else {
            //否则如果要以GB为单位的，先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "GB";
        }
    }

    /**
     * byte to mb 保留两位
     * @param size
     * @return
     */
    public static float getByteToMb(float size) {
        return getByteToMb((long) size);
    }

    public static float getByteToMb(long size) {
        float s = size / 1024 / 1024;
        float num = (float) (Math.round(s * 100) / 100);
        return num;
    }



    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }

    /**
     * 获取手机型号
     * @return
     */
    public static String getSystemModel() {
        return Build.MODEL;
    }

    public static String getOSVersion() {
        return Build.VERSION.RELEASE;
    }

    @SuppressLint("MissingPermission")
    public static String getDeviceUUID(Context ctx) {
        TelephonyManager telephonyManager = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //操蛋 获取deviceId会有问题，直接拿手机厂商跟型号去生成
                UUID deviceUuid = new UUID(getDeviceBrand().hashCode(), ((long) getSystemModel().hashCode() << 32));
                return deviceUuid.toString();
            } else {
                String serialNumber = android.os.Build.SERIAL;
                UUID deviceUuid = new UUID(serialNumber.hashCode(), ((long)telephonyManager.getDeviceId().hashCode() << 32));
                return deviceUuid.toString();
            }
        }
        return "";
    }
    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPenGPS(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }
    /**
     * 强制帮用户打开GPS
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查是否需要更新
     * 0 不需要更新
     * 1 需要强制更新
     * 2 需要可选更新
     * @param context
     * @return
     */
    public static int checkVersion(Context context,Integer newVersionCode,String isForce){
        int oldVersionCode=getVersionCode(context);
        if(newVersionCode>oldVersionCode){
            if(isForce.equals("true")){
                return 1;
            }else {
                return 2;
            }
        }
        return 0;
    }
    /**
     * 将版本转成版本号方便比较大小
     * @param version
     * @return
     */
    public static int getVersionCode(String version){
        version = version.substring(0, version.indexOf(".",version.indexOf(".")+1 ));
        version = version.replaceAll("\\.", "");
        try{
            return Integer.parseInt(version);
        }catch(Exception e){

        }
        return 0 ;
    }
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }

    /**
     * 数组转列表
     * @param str
     * @return
     */
    public static List<String> strArrayToList(String[] str){
        List<String> arr = new ArrayList<>();
        if(str!=null){
            for(String s:str){
                arr.add(s);
            }
        }
        return arr;
    }

    /**
     *  获取状态栏高度
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    /**
     * 将一串文字每个字之间加一个空格
     * @param para
     * @return
     */
    public static String appendSpace(String para){
        if(para==null){
            return "";
        }
        int length = para.length();
        if(length==0){
            return "";
        }
        char[] value = new char[length << 1];
        for (int i=0, j=0; i<length; ++i, j = i << 1) {
            value[j] = para.charAt(i);
            value[1 + j] = ' ';
        }
        String v = new String(value);
        return v.substring(0,v.length()-1);
    }


    /**
     * 获取工单状态名称
     * @param stat
     * @return
     */
    public static String getStatName(int stat){
        switch (stat){
            case 1100:
                return "保存";
            case 1110:
                return "作废";
            case 1120:
                return "可转结算";
            case 1121:
                return "超保不结算";
            case 1140:
                return "异常数据";
            case 5010:
                return "已汇总";
        }
        return "";
    }

    public static boolean isIncludes(int[] data,int v){
        if(data!=null){
            for(int i:data){
                if(i==v){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取字节长度
     * @param s
     * @return
     */
    public static int getWordCount(String s) {
        int length = 0;
        for(int i = 0; i < s.length(); i++) {
            int ascii = Character.codePointAt(s, i);
            if(ascii >= 0 && ascii <=255)
                length++;
            else
                length += 2;
        }
        return length;
    }

    /**
     *  unicode转utf8
     * @param theString
     * @return
     */
    public static String unicodeToUtf8(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len;) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    /**
     *  根据分页大小和总数量 获取总页数
     * @param allCount
     * @param pageSize
     * @return
     */
    public static int getAllPage(int allCount,int pageSize){
        return  (allCount-1)/pageSize+1 ;
    }
}
